<template>
	<el-drawer v-model="visible" :title="!dataForm.id ? '新增' : '修改'">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
			<el-form-item label="仓库代码" prop="warehouseCode">
				<el-input v-model="dataForm.warehouseCode" placeholder="仓库代码"></el-input>
			</el-form-item>
			<el-form-item label="仓库名称" prop="name">
				<el-input v-model="dataForm.name" placeholder="仓库名称"></el-input>
			</el-form-item>
			
			<el-form-item label="仓库地址" prop="address">
				<el-input v-model="dataForm.address" placeholder="仓库地址"></el-input>
			</el-form-item>
			<el-form-item label="仓库网址" prop="links">
				<el-input v-model="dataForm.links" placeholder="仓库网址" type="textarea"></el-input>
			</el-form-item>
			<el-form-item label="仓库描述" prop="comment">
				<el-input v-model="dataForm.comment" placeholder="描述" type="textarea"></el-input>
			</el-form-item>
			<!-- <el-form-item label="仓库描述" prop="masterUserId">
				<el-input v-model="dataForm.masterUserId" placeholder=""></el-input>
			</el-form-item> -->
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useWarehouseApi, useWarehouseSubmitApi } from '@/api/erp/warehouse'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()

const dataForm = reactive({
	id: '',
	name: '',
	address: '',
	warehouseCode: '',
	links: '',
	comment: '',
	masterUserId: ''
})

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
	//id存在则为修改
	if (id) {
		getWarehouse(id)
	}
}

const getWarehouse = (id: number) => {
	useWarehouseApi(id).then(res => {
		Object.assign(dataForm, res.data)
	})
}

const dataRules = ref({
	name: { required: true, message: '仓库名称不能为空', trigger: 'blur' },
	address: { required: true, message: '仓库地址不能为空', trigger: 'blur' },
	warehouseCode: { required: true, message: '仓库代码不能为空', trigger: 'blur' },
	masterUserId: { required: true, message: '仓库管理员不能为空', trigger: 'blur' }
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		useWarehouseSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
